<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>产品介绍</h3>
      <el-form ref="product" :rules="rules" :model="products" label-width="150px">
        <el-form-item label="产品ID" prop="id">
          <el-input v-model="products.id" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="products.name" />
        </el-form-item>

        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="products.isShow">
            <el-radio :label="true">显示</el-radio>
            <el-radio :label="false">不显示</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="products.img" :src="products.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="所属分类">
          <el-cascader ref="myCascader" v-model="categoryIds" :options="categoryList" clearable expand-trigger="hover" @change="handleCategoryChange" />
        </el-form-item>

        <el-form-item label="产品规格">
          <el-input v-model="products.specifications" />
        </el-form-item>

        <el-form-item label="产品功效">
          <el-input v-model="products.effect" />
        </el-form-item>

        <el-form-item label="产品详细介绍">
          <editor v-model="products.desc" :init="editorInit" />
        </el-form-item>
      </el-form>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新产品</el-button>
    </div>

  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.op-container {
  display: flex;
  justify-content: center;
}
</style>

<script>
import { detailProduct, editProduct, listCategory } from '@/api/webproduct'
import { createStorage, uploadPath } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'ProductEdit',
  components: { Editor },
  data() {
    return {
      uploadPath,
      categoryList: [],
      categoryIds: [],
      products: { gallery: [] },
      specVisiable: false,
      productVisiable: false,
      rules: {
        name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        height: '400px',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      if (this.$route.query.id == null) {
        return
      }
      const productId = this.$route.query.id
      detailProduct(productId).then(response => {
        this.products = response.data.data.product
        this.categoryIds = [response.data.data.product.cid]
      })

      listCategory().then(response => {
        this.categoryList = response.data.data.categoryList
      })
    },
    handleCategoryChange(value) {
      this.products.cid = value[value.length - 1]
      this.products.cname = this.$refs.myCascader.getCheckedNodes()[0].pathLabels[0]
    },
    handleCancel: function() {
      this.$router.push({ path: '/web/webproduct' })
    },
    handleEdit: function() {
      const finalGoods = {
        products: this.products
      }
      editProduct(finalGoods)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
          this.$router.push({ path: '/web/webproduct' })
        })
        .catch(response => {
          MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
        })
    },
    uploadPicUrl: function(response) {
      this.products.img = response.data.url
    }
  }
}
</script>
